package com.zjf.carpark.controller;


import com.zjf.carpark.entities.AccessIncome;
import com.zjf.carpark.entities.AccessInfo;
import com.zjf.carpark.entities.AccessNum;
import com.zjf.carpark.service.impl.AccessInfoServiceImpl;
import com.zjf.carpark.service.impl.ICcardServiceImpl;
import com.zjf.carpark.service.impl.ParkPlaceServiceImpl;
import com.zjf.carpark.utils.ResponseData;
import com.zjf.carpark.vo.AccessByCarNumVo;
import com.zjf.carpark.vo.AccessInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.zjf.carpark.utils.CodeAndMessage.*;


/**
 * @description:
 * @author: 张建飞
 * @createDate: 2020/1/3
 * @version: 1.0
 */

@Controller
@RequestMapping("accessInfo")
public class AccessInfoController {

    @Autowired
    AccessInfoServiceImpl accessInfoService;

    @Autowired
    ICcardServiceImpl iCcardService;

    @Autowired
    ParkPlaceServiceImpl parkPlaceService;

    ResponseData responseData = new ResponseData(CODE0, ERROR);

    // 计算时间差
    String sub(Date in, Date out) {
        try {
            long diff = out.getTime() - in.getTime();//这样得到的差值是毫秒级别
            long days = diff / (1000 * 60 * 60 * 24);

            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
            System.out.println("" + days + "天" + hours + "小时" + minutes + "分");
            return "" + days + "天" + hours + "小时" + minutes + "分";
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }

    /**
     * 添加新的入场信息
     *
     * @param data
     * @return
     */
    @RequestMapping("add")
    @ResponseBody
    public ResponseData add(@RequestBody Map<String, String> data) {
        String carNum = data.get("carNum");
        String inImg = data.get("inImg");
        int i = iCcardService.selectByCarNum(carNum);
        String type = "";
        AccessInfo accessInfo = new AccessInfo();
        accessInfo.setCarNum(carNum);
        accessInfo.setInDate(new Date());
        accessInfo.setInImg(inImg);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //获取当前时间并作为时间戳
        String accessId = simpleDateFormat.format(new Date());
        accessInfo.setAccessId(accessId);
        if (i == 0) {
            type = "临时停车用户";
            accessInfo.setType(type);
            Integer save = accessInfoService.save(accessInfo);
            if (save != null) {
                List<String> strings = parkPlaceService.selectEmploy();
                int randomIndex = (int) (Math.random()*strings.size());
                String parkPlace = strings.get(randomIndex);
                System.out.println(parkPlace);
                int i1 = parkPlaceService.inUpdateParkPlace(carNum,parkPlace);
                responseData = new ResponseData(CODE200, SUCCESS);
                responseData.putDataValue("type", type);
                responseData.putDataValue("parkPlace", parkPlace);
            } else {
                return responseData;
            }
        } else {
            double price = 0;
            type = "固定停车用户";
            accessInfo.setType(type);
            accessInfo.setCost(price);
            Integer save = accessInfoService.save(accessInfo);
            if (save != null) {
                String parkPlace = parkPlaceService.selectParkPlaceByCarNum(carNum);
                responseData = new ResponseData(CODE200, SUCCESS);
                responseData.putDataValue("type", type);
                responseData.putDataValue("parkPlace", parkPlace);
            } else {
                return responseData;
            }
        }
        return responseData;
    }

    /**
     * 出场
     *
     * @param carNum
     * @param outImg
     * @return
     */
    @RequestMapping("out")
    @ResponseBody
    public ResponseData out(String carNum, String outImg) {
        AccessInfo accessInfo = accessInfoService.selectByCarNum(carNum);
        accessInfo.setOutDate(new Date());
        double diff = accessInfo.getOutDate().getTime() - accessInfo.getInDate().getTime();//这样得到的差值是微秒级别
        double hours = diff / (1000 * 60 * 60);
        double price = 3 * Math.round(hours);
        AccessInfo accessInfo1 = new AccessInfo();
        accessInfo1.setCarNum(carNum);
        accessInfo1.setOutDate(accessInfo.getOutDate());
        accessInfo1.setCost(price);
        accessInfo1.setOutImg(outImg);
        String stayTime = sub(accessInfo.getInDate(), accessInfo.getOutDate());
        int out = accessInfoService.out(accessInfo1);
        if (out != 0) {
            int i = parkPlaceService.outUpdateParkPlace(carNum);
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("price", price);
            responseData.putDataValue("type", accessInfo.getType());
            responseData.putDataValue("stayTime", stayTime);
        }
        return responseData;
    }

    /**
     * 查询所有临时车出入场情况
     *
     * @return
     */
    @RequestMapping("selectAllLinShi")
    @ResponseBody
    public ResponseData selectAllLinShi(HttpServletResponse response, AccessInfoVO accessInfoVo) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        List<AccessInfo> accessInfos = accessInfoService.selectAllLinShi(accessInfoVo);
        int totalCount = accessInfoService.totalCount(accessInfoVo);
        if (accessInfos != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("accessInfos", accessInfos);
            responseData.setCount(totalCount);
        }
        return responseData;
    }

    /**
     * 查询所有的固定车主的出入场信息
     *
     * @param accessInfoVo
     * @return
     */
    @RequestMapping("selectAllFixed")
    @ResponseBody
    public ResponseData selectAllFixed(AccessInfoVO accessInfoVo) {
        List<AccessInfo> accessInfos = accessInfoService.selectAllFixed(accessInfoVo);
        int count = accessInfoService.fixedTotalCount(accessInfoVo);
        if (accessInfos != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("accessInfos", accessInfos);
            responseData.setCount(count);
        }
        return responseData;
    }

    /**
     * 查询停车出入量
     *
     * @param data
     * @return
     */
    @RequestMapping("selectCount")
    @ResponseBody
    public ResponseData selectCount(@RequestBody Map<String, Integer[]> data) {
        Integer[] begin = data.get("begin");
        Integer[] end = data.get("end");
        //每一天的停车出入量
        List<Integer> counts = new ArrayList<>();
        //对应的日期
        List<String> dates = new ArrayList<>();
        Date date = new Date();
        //遍历时间
        for (int i = 0; i < begin.length; i++) {
            DateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            String now = subDay(format.format(date), -i);
            System.out.println(begin[i]);
            //查询出对应日期的流量
            int count = accessInfoService.selectCount(begin[i], end[i]);
            counts.add(count);
            dates.add(now);
        }

        if (counts != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("count", counts);
            responseData.putDataValue("dates", dates);
        }
        return responseData;
    }

    /**
     * 查询一年的每月流量
     *
     * @param data
     * @return
     */
    @RequestMapping("selectNumByYear")
    @ResponseBody
    public ResponseData selectNumByYear(@RequestBody Map<String, Integer> data) {
        Integer year = data.get("year");
        System.out.println(year);
        List<AccessNum> accessNums = accessInfoService.selectCountByYear(year);
        if (accessNums != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("accessNums", accessNums);
        }
        return responseData;
    }

    /**
     * 计算天数
     *
     * @param date
     * @param amount
     * @return
     */
    private String subDay(String date, Integer amount) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date dt = null;
        try {
            dt = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.DAY_OF_MONTH, amount);
        Date dt1 = rightNow.getTime();
        String reStr = sdf.format(dt1);
        return reStr;
    }

    /**
     * 通过汽车车牌号查询其所有出入信息
     *
     * @param accessByCarNumVo
     * @return
     */
    @RequestMapping("selectAllByCarNum")
    @ResponseBody
    public ResponseData selectAllByCarNum(AccessByCarNumVo accessByCarNumVo) {
        List<AccessInfo> accessInfos = accessInfoService.selectAllByCarNum(accessByCarNumVo);
        int count = accessInfoService.selectCountByCarNum(accessByCarNumVo);
        if (accessInfos != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("accessInfos", accessInfos);
            responseData.setCount(count);
        }
        return responseData;
    }

    /**
     * 通过id查询一条
     *
     * @param data
     * @return
     */
    @RequestMapping("selectByAccessId")
    @ResponseBody
    public ResponseData selectByAccessId(@RequestBody Map<String, String> data) {

        String accessId = data.get("accessId");
        AccessInfo accessInfo = accessInfoService.selectByAccessId(accessId);
        if (accessInfo != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("accessInfo", accessInfo);
        }
        return responseData;
    }

    /**
     * 通过id删除一条
     *
     * @param data
     * @return
     */
    @RequestMapping("deleteByAccessId")
    @ResponseBody
    public ResponseData deleteByAccessId(@RequestBody Map<String, String> data) {

        AccessInfo accessInfo = new AccessInfo();
        accessInfo.setAccessId(data.get("accessId"));
        Integer update = accessInfoService.update(accessInfo);
        if (update != 0) {
            responseData = new ResponseData(CODE200, SUCCESS);
        }
        return responseData;
    }

    /**
     * 查询某一年每月的收入
     *
     * @param data
     * @return
     */
    @RequestMapping("selectIncomeByYear")
    @ResponseBody
    public ResponseData selectIncomeByYear(@RequestBody Map<String, Integer> data) {

        Integer year = data.get("year");
        List<AccessIncome> accessIncomes = accessInfoService.selectIncomeByYear(year);
        if (accessIncomes != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("incomes", accessIncomes);
        }
        return responseData;
    }

    /**
     * 控制台图表渲染数据
     *
     * @return
     */
    @RequestMapping("getData")
    @ResponseBody
    public ResponseData getData(){
        return accessInfoService.getData();
    }
}
